package com.ifonly.activerecord.dialect;

import com.google.common.base.Strings;
import com.ifonly.activerecord.dialect.db.MysqlDialect;
import com.ifonly.activerecord.helpers.SqlInfo;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-18 14:45
 * @since JDK 1.6
 */
public abstract class Dialect {
    public static final String COUNT_KEY = "c";

    public static final String MYSQL             = "mysql";
    public static final String MYSQL_DRIVER      = "com.mysql.jdbc.Driver";

    public static Dialect create(String dialect) {
        if (Strings.isNullOrEmpty(dialect)) {
            throw new IllegalArgumentException("param dialect can not be null or empty");
        }
        if ("mysql".equalsIgnoreCase(dialect)) {
            return new MysqlDialect();
        }
        throw new UnsupportedOperationException("unsupported dialect[" + dialect + "]");
    }

    public static String parseFromUrl(String url) {
        if (url.startsWith("jdbc:mysql:") || url.startsWith("jdbc:cobar:")
                || url.startsWith("jdbc:log4jdbc:mysql:")) {
            return MYSQL;
        }

        return null;
    }

    public abstract String buildTableSql(String tableName);


    /**
     * 将sql转换为分页SQL
     *
     * @param sql    SQL语句
     * @param offset  开始条数
     * @param limit 每页显示多少纪录条数
     * @param params 查询参数
     * @return 分页查询的sql与参数
     */
    public abstract SqlInfo sql(String sql, int offset, int limit, Object... params);

    /**
     * 将sql转换为Count SQL
     *
     * @param sql SQL语句
     * @return Count SQL
     */
    public String count(String sql) {
        return "SELECT count(1) AS " + COUNT_KEY + " FROM (" + sql + ") tmp_count";
    }

}
